package com.mysher.myplugin;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;

import java.io.IOException;

public class HttpUtils {
    public static final String TRANSLATE_BASE_URL = "https://openapi.youdao.com/api";

    public static void doGetAsync(String query, HttpCallback callback) {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(TRANSLATE_BASE_URL)
                .post(YouDaoUtil.params(query))
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFail(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() != null) {
                    String data = response.body().string();
                    System.out.println(data);
                    JsonParser parser = new JsonParser();
                    JsonObject json = (JsonObject) parser.parse(data);
//                    Type genType = getClass().getGenericSuperclass();
//                    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
                    if (json.has("errorCode")) {
                        switch (json.get("errorCode").getAsInt()) {
                            case 0:
                                TranslateBean bean = new Gson().fromJson(json, TranslateBean.class);
                                callback.onSuccess(bean);
                                break;
                            default:
                                callback.onFail("翻译失败：error1");
                                break;
                        }
                    } else {
                        callback.onFail("翻译失败：error2");
                    }
                }
            }
        });

    }



    interface HttpCallback {
        void onSuccess(TranslateBean content);

        void onFail(String errorMsg);
    }
}
